<?php

namespace app\api\controller;

use app\common\controller\Api;
use app\common\library\Alisms;
use app\common\library\WechatPay;
use app\common\model\BasicData;
use app\common\model\Form;
use app\common\model\VoucherGrant;
use think\Log;
use think\Request;
use fast\Http;
use think\Env;
use app\common\model\GrantLog;

/**
 * 首页接口
 */
class Xipingnew extends Api
{
    protected $noNeedLogin = '*';
    protected $noNeedRight = '*';

     public function sms()
    {

        if(time() < 1754668800) $this->error('活动还未开始');
        $mobile = $this->request->post("mobile");
        $activity_id = $this->request->post("activity_id");
        $event  = $this->request->post("event",'get');

        if (!$mobile || !\think\Validate::regex($mobile, "^1\d{10}$")) {
            $this->error(__('手机号不正确'));
        }
        if(GrantLog::where(['form_data'=>['like','%'.$mobile.'%']])->where('activity_id',$activity_id)->whereIn('status',[2,4])->find()){
            $this->error(__('该手机号已领取'));
        }
        $activity = \app\common\model\Activity::where('id',$activity_id)->find();
        if(!$activity){
            $this->error(__('活动不存在'));
        }
        if($activity->form_id > 0){
            $diy_form = json_decode(Form::where('id',$activity->form_id)->value('diy_form'),true);
            foreach ($diy_form as $k=>$v) {
                if($v['format'] == 'phone' && $v['verify_field'] != '无'){
                    $is_not = BasicData::where(['activity_id' => $activity_id, $v['verify_field'] => $mobile])->find();
                    if (!$is_not) {
                        $this->error('无权限领取');
                        break;
                    }
                }
            }
        }
        // $app_key = Env::get('sms.app_key') ?? '545Bv4';
        // $app_code = Env::get('sms.app_code') ?? '1000';
        // $apps_ecret = Env::get('sms.app_secret') ?? 'Ba1167';
        $app_key = 'thkeji';
        $app_code = '1000';
        $apps_ecret = 'NBET92';
        $gateway = Env::get('sms.gateway') ?? 'http://123.57.229.179:9090/sms/batch/v1';
        $tiemstamp = self::getMillisecond();
        $code =  mt_rand(1000, 9999);
        $data = [
            'appkey' => $app_key,
            'appcode'=> $app_code,
            'sign'   => md5($app_key.$apps_ecret.$tiemstamp),
            'phone'  => $mobile,
            'msg'    =>'【农信惠】您的验证码是'.$code.'。如非本人操作，请忽略本短信',
            'timestamp'=>$tiemstamp,
        ];
        $res = Http::post($gateway,json_encode($data),[],['Content-Type: application/json']);
        $result = json_decode($res,true);
        if($result['code'] != '00000'){
            $this->success('发放失败，请稍后重试');
        }else{
            \app\common\model\Sms::create(['event' => $event, 'mobile' => $mobile, 'code' => $code, 'ip' => '', 'createtime' => time()]);
            $this->success('成功');
        }

    }


    public function smsCheck($mobile,$code,$event = 'get')
    {
        $time = time() - 300;
        $sms = \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])
            ->order('id', 'DESC')
            ->find();
        if ($sms) {
            if ($sms['createtime'] > $time && $sms['times'] <= 10) {
                $correct = $code == $sms['code'];

                if (!$correct) {
                    $sms->times = $sms->times + 1;
                    $sms->save();
                    return false;
                } else {
                    $sms->times = $sms->times + 11;
                    $sms->save();
                    return true;
                }
            } else {
                // 过期则清空该手机验证码
                \app\common\model\Sms::where(['mobile' => $mobile, 'event' => $event])->delete();
                return false;
            }
        } else {
            return false;
        }
    }


    public static function getMillisecond(){
        list($msec, $sec) = explode(' ', microtime());

        $msectime = (float)sprintf('%.0f', (floatval($msec) + floatval($sec)) * 1000);

        return $msectimes = substr($msectime,0,13);

    }

}
